<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools show-before>
        <template #before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template #after>
          <el-button
            size="small"
            type="success"
            @click="$router.push('/import')"
          >Excel导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportData"
          >Excel导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>
      <el-card>
        <el-table
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 0.8)"
          :data="list"
          border
        >
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" sortable="" style="width:120px;">
            <template v-slot="{ row: { staffPhoto } }">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="staffPhoto"
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                alt=""
                @click="showStaffPhoto(staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <!--  方式一通过过滤器格式化 -->
          <!-- <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            sortable=""
          >
            <template v-slot="{row}">
              {{ row.formOfEmployment|formOfEmployment }}
            </template>
          </el-table-column> -->
          <!-- 方式二 -->
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formOfEmployment"
          ></el-table-column>
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState === 1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            layout="prev,pager,next"
            @current-change="handleCyrrentChange"
          ></el-pagination>
        </el-row>
      </el-card>
    </div>
    <!-- 放置弹层 -->
    <AddDemployee :show-dialog.sync="showDialog"></AddDemployee>
    <el-dialog
      title="二维码"
      :visible.sync="showCodeDialog"
      width="30%"
    >
      <canvas ref="canvas"></canvas>
    </el-dialog>
    <assign-role ref="assiginRole" :show-role-dialog.sync="showRoleDailog" :user-id="userId"></assign-role>
  </div>
</template>

<script>
import { delEmployee, getEmployeeList } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
// 引入弹层
import AddDemployee from './components/add-employee.vue'
import { pick } from 'lodash'
import { formatDate } from '@/filters'
// 引入依赖
// const QRCode = require('qrcode')
import QRCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: { AddDemployee, AssignRole },
  // 过滤器
  filters: {
    formOfEmployment(val) {
      const f = EmployeeEnum.hireType.find(t => t.id === val)
      return f ? f.value : '未知'
    }
  },
  props: {},
  data() {
    return {
      loading: false,
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 10,
        total: 0 // 总数
      },
      showDialog: false, // 控制弹层
      showCodeDialog: false, // 二维码弹层
      showRoleDailog: false, // 显示分配角色弹层
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  mounted() {},
  methods: {
    async editRole(id) {
      this.userId = id
      await this.$refs.assiginRole.getUserDetailById(id)
      this.showRoleDailog = true
    },
    showStaffPhoto(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          const canvas = this.$refs.canvas
          QRCode.toCanvas(canvas, url, function(error) {
            if (error) console.error(error)
            // console.log('success!')
          })
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    exportData() {
      // 映射数据
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        // 得到数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const values = Object.values(headers)
        console.log(values)
        const results = rows.map(o => {
          const t = pick(o, values)
          t.timeOfEntry = formatDate(t.timeOfEntry)
          t.correctionTime = formatDate(t.correctionTime)
          const f = EmployeeEnum.hireType.find(s => s.id === o.formOfEmployment)
          t.formOfEmployment = f ? f.value : '未知'
          return Object.values(t)
        })
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        // 得到映射数据
        console.log(Object.keys(headers))
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: results, // 具体数据 必填
          filename: '工资表', // 非必填
          multiHeader,
          merges
        })
      })
    },
    delEmployee(id) {
      // 确认 ,通过elmecon
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(async action => {
        // 发请求
        await delEmployee(id)
        // 提示成功,通过elme
        this.$message({
          message: '操作成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
        // 刷新页面
        this.getEmployeeList()
      }).catch(() => {

      })
    },
    // el里自带的格式化时间
    formOfEmployment(row, colum, val, index) {
      const f = EmployeeEnum.hireType.find(t => t.id === val)
      return f ? f.value : '未知'
    },
    handleCyrrentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
